package guyubao.com.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import guyubao.com.entity.RestBean;
import guyubao.com.service.AccountService;
import guyubao.com.utils.Const;
import guyubao.com.utils.JwtUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/***
 * 禁用用户拦截
 */
@Component
@Order(Const.ORDER_DISABLE)
public class DisableFilter extends HttpFilter {
    @Resource
    JwtUtils utils;
    @Resource
    AccountService accountService;
    @Override
    protected void doFilter(HttpServletRequest request,
                            HttpServletResponse response,
                            FilterChain filterChain) throws IOException, ServletException {
        //首先从Header中取出JWT
        String authorization = request.getHeader("Authorization");
        DecodedJWT jwt = utils.resolveJwt(authorization);
        // 中国时区
        TimeZone chinaTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(chinaTimeZone);
        //判断是否包含JWT且格式正确
        if (jwt!=null) {
            String id = utils.toId(jwt);
            Date disabledTime = accountService.getDisableTimeById(id);
            // 如果为空就放行
            if (disabledTime!=null){
                // 如果时间是否晚于当前时间就拦截
                if(disabledTime.after(new Date())) {
                    this.writeBlockMessage(response,disabledTime);
                } else {
                    filterChain.doFilter(request, response);
                }
            }else {
                filterChain.doFilter(request, response);
            }
        }else {
            filterChain.doFilter(request, response);
        }
    }
    /**
     * 为响应编写拦截内容
     * @param response 响应
     * @throws IOException 可能的异常
     */
    private void writeBlockMessage(HttpServletResponse response,Date disabledTime) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter writer = response.getWriter();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(disabledTime);
        writer.write(RestBean.forbidden("您已被封禁！"+format+"之后才解封,如已解封请重新登录").asJsonString());
    }
}